﻿/*
 * Description: 字符串常用操作
 */
#include "text_util/string_proc.h"

#include <Windows.h>
#include <map>
#include <regex>

namespace StringProc {
    std::wstring StringToWString(const std::string& value)
    {
        int len = static_cast<int>(value.length());
        int resultLen = MultiByteToWideChar(CP_ACP, 0, value.c_str(), len, nullptr, 0);
        if (resultLen == 0) {
            return L"";
        }
        std::wstring wstr(resultLen, L'\0');
        MultiByteToWideChar(CP_ACP, 0, value.c_str(), len, const_cast<LPWSTR>(wstr.c_str()), resultLen);
        return wstr;
    }

    std::string WStringToString(const std::wstring& wstr)
    {
        int len = static_cast<int>(wstr.length());
        int resultLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), len, nullptr, 0, nullptr, nullptr);
        if (resultLen == 0) {
            return "";
        }
        std::string value(resultLen, '\0');
        WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), len, const_cast<LPSTR>(value.c_str()),
                            resultLen, nullptr, nullptr);
        return value;
    }

    std::wstring StringToWStringByUTF8(const std::string& value)
    {
        int len = static_cast<int>(value.length());
        int retLen = MultiByteToWideChar(CP_UTF8, 0, value.c_str(), len, nullptr, 0);
        if (retLen == 0) {
            return L"";
        }
        std::wstring wstr(retLen, L'\0');
        MultiByteToWideChar(CP_UTF8, 0, value.c_str(), len, (LPWSTR)wstr.c_str(), retLen);
        return wstr;
    }

    std::string WStringToStringByUTF8(const std::wstring& wstr)
    {
        int len = static_cast<int>(wstr.length());
        int retLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, nullptr, 0, nullptr, nullptr);
        if (retLen == 0) {
            return "";
        }
        std::string value(retLen, '\0');
        WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, const_cast<LPSTR>(value.c_str()),
                            retLen, nullptr, nullptr);
        return value;
    }

    std::string StringTrim(const std::string& s)
    {
        if (s.empty()) {
            return s;
        }
        std::string ret = s;
        ret.erase(0, ret.find_first_not_of(" "));
        ret.erase(ret.find_last_not_of(" ") + 1);
        return ret;
    }

    std::wstring WStringTrim(const std::wstring& s)
    {
        if (s.empty()) {
            return s;
        }
        std::wstring ret = s;
        ret.erase(0, ret.find_first_not_of(L" "));
        ret.erase(ret.find_last_not_of(L" ") + 1);
        return ret;
    }
} // namespace StringProc